package com.ys.controller.api.base;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.bo.annotation.Model;
import com.ys.config.MenuId;
import com.ys.entity.base.TbUserPaySlip;
import com.ys.entity.sys.YsCol;
import com.ys.service.base.TbUserPaySlipService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 员工工资条信息表
 */
@Controller
@RequestMapping("/api/inter/tbUserPaySlip")
public class ApiInterTbUserPaySlipController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTbUserPaySlipController.class);

    @Autowired
    private CommonApiService<TbUserPaySlip> commonApiService;

    @Autowired
    private TbUserPaySlipService tbUserPaySlipService;

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TbUserPaySlip setSeachSql(TbUserPaySlip cond){

        cond.addLeftJoin("TS_UserInfo U ON U.UserId = A.UserId")//用户信息表
                .addField("(U.UserId + '/' + U.UserName) AS _ys_nameLinked")//工号/姓名

                .addLeftJoin("TS_OrganizationInfo O ON O.OrgId = A.OrgId")//组织机构表
                .addField("O.OrgName AS orgName,O.orgId AS orgId");//所属公司

        cond.addLeftJoin("TB_UserMonthPerformance MP ON MP.Id = A.MonthPerformanceId")//员工月度绩效信息表
                .addField("MP.Rank AS rank")//岗位职级
                .addField("MP.Type AS type")//岗位工种(0总经理 1副总经理 2责任月薪型员工 3绩效提奖型员工 4研发人员)
                .addField("MP.JobBonus AS jobBonus")//岗位提奖/月
                .addField("MP.DeptName AS deptName")//部门
                .addField("MP.UserState AS userState")//员工状态
                .addField("MP.Category AS category")//岗位类别
                .addField("MP.Categories AS categories")//职级大类(0A 1B 2C 3D 4P)

                .addField("MP.FixsalaryStandard AS fixsalaryStandard")//定薪标准
                .addField("MP.SalaryStandard AS salaryStandard")//发薪标准
                .addField("MP.BasicSalary AS basicSalary")//基本底薪
                .addField("MP.PositionSalary AS positionSalary")//岗位薪资
                .addField("MP.TransSubsidy AS transSubsidy")//交通补贴
                .addField("MP.CateringSubsidy AS cateringSubsidy")//餐饮补贴

        ;
        /*
        cond.addLeftJoin("TB_JobLevel JB ON JB.Id = A.RoleLevelId")//岗位职级管理表
                .addField("JB.FixsalaryStandard AS fixsalaryStandard")//定薪标准
                .addField("JB.SalaryStandard AS salaryStandard")//发薪标准
                .addField("JB.BasicSalary AS basicSalary")//基本底薪
                .addField("JB.PositionSalary AS positionSalary")//岗位薪资
                .addField("JB.TransSubsidy AS transSubsidy")//交通补贴
                .addField("JB.CateringSubsidy AS cateringSubsidy")//餐饮补贴

        ;

         */

        //排序
        cond.setOrderby("A.PointMonth DESC,A.UserId ASC");
        //权限
        cond = commonApiService.dataAuth(MenuId.TB_UserPaySlip, cond);
        return cond;
    }

    //处理返回的数据
    public List setList(List<Map<String, Object>> resDate){
        List<Map<String, Object>> tableDate = new ArrayList();
        resDate.forEach(setItem->{
            BigDecimal attendancePerformance = new BigDecimal(setItem.get("attendancePerformance").toString()) ;
            setItem.put("attendancePerformance",String.format("%.2f", BigDecimal.ZERO.subtract(attendancePerformance)));
            tableDate.add(setItem);
        });
        return tableDate;
    }


    /**
     * 查询
     */
    @RequiresPermissions("tbUserPaySlip:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TbUserPaySlip cond,String conditions
    ){
        try {
            cond = setSeachSql(cond);
            //查询条件
            String nameLinked = ConditionUtil.getConditionValue(conditions, "_ys_nameLinked");//工号/姓名
            if (nameLinked != null){
                cond.where("U.UserId LIKE '%" + nameLinked + "%'" + " OR  U.UserName LIKE '%" + nameLinked + "%'");
            }
            LayuiTableVoJA tableVoJA = commonApiService.searchLay(cond);
            //获取
            JSONArray tableVoJAData = tableVoJA.getData();
            //转换
            List<Map> resList = JSONArray.parseArray(JSON.toJSONString(tableVoJAData),Map.class);
            List<Map<String, Object>> resListNew = new ArrayList();
            resList.forEach(item-> resListNew.add(item));

            //处理数据
            resList = setList(resListNew);
            JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(resList));
            tableVoJA.setData(jsonArray);

            return tableVoJA;

            //return tableVoJA;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }


    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TbUserPaySlip cond){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond);
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(MenuId.TB_UserPaySlip)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();

            //处理数据
            ExportExcelUtils<TbUserPaySlip> util = new ExportExcelUtils<>(new TbUserPaySlip());
            String toFilePath = util.exportExcel(listData, listField, "员工工资条信息表");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }

    /**
     * 保存
     */
    @RequestMapping("/toSave")
    @ResponseBody
    public R toSave(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            //编辑
            return tbUserPaySlipService.save(params,MenuId.TB_UserPaySlip);
        } catch (Exception e) {
            logger.error("修改出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }

    /**
     * 删除
     */
    @RequestMapping("/toDel")
    @ResponseBody
    public R toDel(HttpServletRequest request,@RequestParam Map<String, Object> params){
        try {
            String ids = params.get("ids").toString();
            String[] idArr = ids.split(",");
            List<String> idList = new ArrayList<>();
            Collections.addAll(idList,idArr);
            int count = 0;
            //删除
            for (int i = 0; i < idList.size(); i++) {
                R res= tbUserPaySlipService.del(Long.parseLong(idList.get(i)));
                if(res.getCode()==0){
                    count ++;
                }
            }
            String backMsg = "成功删除"+count+"条！";
            if(idList.size()!=count){
                backMsg+="（工资状态为“空”才可删除）";
            }
            return R.ok(backMsg);
        } catch (Exception e) {
            logger.error("删除出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }

    /**
     * 员工工资条(员工工资申请调用)
     */
    @RequestMapping("/searchForModalAp")
    @ResponseBody
    public LayuiTableVoJA searchForModalAp(Model model, HttpServletRequest request, HttpServletResponse response,
    		@ModelAttribute TbUserPaySlip cond
    ){
        try {
            cond = setSeachSql(cond)
            .where("(SELECT count(1) FROM TB_UserPayApplyItem WHERE UserPaySlipidid = A.Id) = 0 AND A.SlipStatus = 1")
            .addField("MP.perbasedSalary AS perbasedSalary")//绩效薪资
            .addField("MP.quarterlyBonus AS quarterlyBonus")//季度提奖
            .addField("MP.annualBonus AS annualBonus")//年终奖
            .addField("A.id AS userPaySlipidid")//主键id
            .addField("O.orgName+A.pointMonth AS orgNamePointMonth");//判断重复使用

            LayuiTableVoJA tableVoJA = commonApiService.searchLay(cond);
            return tableVoJA;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }

    /**
     * 个税导入
     */
    @RequestMapping("/importUserTax")
    @ResponseBody
    public R importUserTax(HttpServletRequest request,@RequestParam Map<String, Object> params){
        try {
            String ids = params.get("ids").toString();
            String[] idArr = ids.split(",");
            List<String> idList = new ArrayList<>();
            Collections.addAll(idList,idArr);
            int count = 0;
            //个税导入
            for (int i = 0; i < idList.size(); i++) {
                R res= tbUserPaySlipService.importUserTax(Long.parseLong(idList.get(i)));
                if(res.getCode()==0){
                    count ++;
                }
            }
            String backMsg = "成功导入"+count+"条！";
            if(idList.size()!=count){
                backMsg+="（工资状态为“空”才可导入）";
            }
            return R.ok(backMsg);
        } catch (Exception e) {
            logger.error("个税导入出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }

    /**
     * 年终奖导入
     */
    @RequestMapping("/importYearEndBonus")
    @ResponseBody
    public R importYearEndBonus(HttpServletRequest request,@RequestParam Map<String, Object> params){
        try {
            String ids = params.get("ids").toString();
            String[] idArr = ids.split(",");
            List<String> idList = new ArrayList<>();
            Collections.addAll(idList,idArr);
            int count = 0;
            //年终奖导入
            for (int i = 0; i < idList.size(); i++) {
                R res= tbUserPaySlipService.importYearEndBonus(Long.parseLong(idList.get(i)));
                if(res.getCode()==0){
                    count ++;
                }
            }
            String backMsg = "成功导入"+count+"条！";
            if(idList.size()!=count){
                backMsg+="（年终奖限制一年一次，并且工资状态为“空”才可导入）";
            }
            return R.ok(backMsg);
        } catch (Exception e) {
            logger.error("年终奖导入出错：",e.getMessage(),e);
            return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
        }
    }



}